package socdev.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;

public class TasksContainer implements Runnable {

	Map<String, Task> tasks = new HashMap<String, Task>();
	User user;
	Project project;
	Handler handler;
	Runnable handlerRunnable;
	static boolean isUpdating;

	public TasksContainer(User user, Project project) {
		this.user = user;
		this.project = project;
		isUpdating = false;
	}

	public synchronized void update(Handler handler, Runnable runnable) {
		if (isUpdating)
			return;
		isUpdating = true;
		Thread update = new Thread(this);

		this.handler = handler;
		this.handlerRunnable = runnable;

		update.start();

	}

	@Override
	public void run() {
		try {
			JSONArray jsonArray = JSonDownloader
					.getData(
							"http://socdev-dev1.appspot.com/api/tasks/",
							project.getNameValuePairs(user
									.getNameValuePairs(new ArrayList<NameValuePair>())));
			tasks = new HashMap<String, Task>();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				Task task = Task.createFromJson(jsonObject);
				tasks.put(task.getId(), task);
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}

		this.handler.post(handlerRunnable);
		isUpdating = false;
	}

	public boolean contains(String id) {
		return tasks.containsKey(id);

	}

	public Task get(String id) {
		return tasks.get(id);
	}

	public List<Task> getAll() {
		return new ArrayList<Task>(tasks.values());

	}

}
